<?php 
///////
// IdleIRC - 2020
// (C) Chris Dorman, GPLv3
// https://notabug.org/Pentium44/idleirc
///////

// server.php - used to communicate between web frontend and irc client
// Grabs from IRC client output
// Pushes to IRC client input

// Include PHP config file with server, title, and channel settings
include_once("config.php");

session_start();

$username = $_SESSION['idleirc-user'];
$usernick = $_SESSION['idleirc-nick'];
$acctpass = $_SESSION['idleirc-pass'];
$channel = $_SESSION['idleirc-channel'];
$servaddr = $_SESSION['idleirc-servaddr'];
$servport = $_SESSION['idleirc-servport'];

// If we have a message; grab user and content and push to IRC client
if (isset($_GET['msg']) && $_GET['msg']!="" && isset($_GET['nick']) && $_GET['nick']!=""){		
	$nick = $usernick; // Usernick
	$msg  = rawurldecode(stripslashes(trim($_GET['msg']))); // User message content
	$line = ""; // start with nothing
	$logline = ""; // start with nothing

	// Seperate message input via space
	$cmd = explode(" ", $msg);
	if($cmd[0]=="/msg") { // If using /msg, push private message
		$prvmsg = array_splice($cmd, 2); // grab private message from string
		$line .= "PRIVMSG" . " " . trim($cmd[1]) . " :"; // set for push
		$x = 0;
		$logline .= "<tr><td class='userinfo'><b>$nick</b>: " . trim($cmd[1]) . ": </td><td>";
		foreach($prvmsg as $word) {
			// Grab each word in the array after the privmsg username
			if($x == 0) {
				$line .= $word;
				$logline .= $word;
			} else {
				$line .= " " . $word;
				$logline .= " " . $word;
			}
			$x++;
		}
		$line .= "\n";
		$logline .= "</td></tr>\n";
	} else if($cmd[0]=="/me") { // If using /msg, push private message
		$prvmsg = array_splice($cmd, 1); // grab private message from string
		$line .= "PRIVMSG" . " " . $channel . " :\x01ACTION "; // set for push
		$x = 0;
		$logline .= "<tr><td class='userinfo'><b>$channel:</b></td><td> $nick ";
		foreach($prvmsg as $word) {
			// Grab each word in the array after the privmsg username
			if($x == 0) {
				$line .= $word;
				$logline .= $word;
			} else {
				$line .= " " . $word;
				$logline .= " " . $word;
			}
			$x++;
		}
		$logline .= "</td></tr>\n";
		$line .= "\x01\n";
	} else if ($cmd[0]=="/join") {
		doLog("$username: joining " . $cmd[1]);
		$line .= "JOIN " . trim($cmd[1]) . "\n"; // set for push
		//$logline .= "<tr><td class='userinfo'><b>$nick</b>:</td><td>Joining " . $cmd[1] . "</td></tr>\n"; // push to client
		$_SESSION['idleirc-channel'] = trim($cmd[1]);
	} else if ($cmd[0]=="/channel" || $cmd[0]=="/focused") {
        doLog("$username: checking focused channel: " . $channel);
        $logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Focused on $channel</td></tr>\n"; // push to client
    } else if ($cmd[0]=="/nick") {
		if($cmd[1]!="") {
	        doLog("$username: setting nick to " . $cmd[1]);
	        $line .= "NICK " . trim($cmd[1]) . "\n"; // set for push
			$_SESSION['idleirc-nick'] = trim($cmd[1]);
		} else {
			$logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Joining " . $cmd[1] . "</td></tr>\n";
		}
    } else if ($cmd[0]=="/usermode") {
        if($cmd[1]!="") {
            doLog("$username: setting usermode to " . $cmd[1]);
            $line .= "MODE $nick +x" . trim($cmd[1]) . "\n"; // set for push
        } else {
            $logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Missing User MODE flags<br /> /usermode [flag(s)]</td></tr>\n";
        }
    } else if ($cmd[0]=="/archive") {
        if(file_exists("users/$username.logcount")) {
            $archivedLogCount = file_get_contents("users/$username.logcount");
            $archivedLogCount++;
            file_put_contents("users/$username.logcount", $archivedLogCount);
            rename("users/$username.log", "users/$username.$archivedLogCount.log");
            $logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Logs are archived! View under 'IRC logs'</td></tr>\n";
        } else {
            file_put_contents("users/$username.logcount", "1");
            rename("users/$username.log", "users/$username.1.log");
            $logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Logs are archived! View under 'IRC logs'</td></tr>\n";
        }
    } else if ($cmd[0]=="/mode") {
        if($cmd[1]!="") {
			if($cmd[2]!="") {
	 			doLog("$username: setting nick to " . $cmd[1]);
				$line .= "MODE " . trim($cmd[1]) . " " . trim($cmd[2]) . "\n"; // set for push
			} else {
				$logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Missing MODE flags:<br /> /mode [channel] [flag(s)]</td></tr>\n";
			}
		} else {
            $logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>Missing channel and flags:<br /> /mode [channel] [flag(s)]</td></tr>\n";
		}
    } else if ($cmd[0]=="/list") {
		if($cmd[1]!="") {
			doLog("$username: listing users for " . $cmd[1]);
			$line .= "NAMES " . trim($cmd[1]) . "\n"; // set for push
        } else {
			doLog("$username: listing users for $channel");
            $line .= "NAMES $channel\n"; // set for push
		}
    } else if ($cmd[0] == "/rejoin") {
		doLog("$username: rejoining channel");
        if ($cmd[1] != "") {
            $line .= "PART " . trim($cmd[1]) . " :$username leaving...\n"; // push close command to IRC
			$line .= "JOIN " . trim($cmd[1]) . "\n"; // set for push
            //$logline .= "<tr><td class='userinfo'><b>$nick</b>: </td><td>Leaving " . trim($cmd[1]) . "</td></tr>\n"; // push to client
        } else {
            $line .= "PART $channel :$username leaving...\n"; // push close command to IRC
			$line .= "JOIN $channel\n"; // set for push
            //$logline .= "<tr><td class='userinfo'><b>$nick</b>: </td><td>Leaving $channel</td></tr>\n"; // push to client
        }
	} else if ($cmd[0] == "/part") {
		doLog("$username: leaving " . trim($cmd[1]));
		if ($cmd[1] != "") {
	        $line .= "PART " . trim($cmd[1]) . " :$nick leaving...\n"; // push close command to IRC
	        //$logline .= "<tr><td class='userinfo'><b>$nick</b>: </td><td>Leaving " . trim($cmd[1]) . "</td></tr>\n"; // push to client
		} else {
			$line .= "PART $channel :$username leaving...\n"; // push close command to IRC
            //$logline .= "<tr><td class='userinfo'><b>$nick</b>: </td><td>Leaving $channel</td></tr>\n"; // push to client
		}
	} else if ($cmd[0] == "/focus" || $cmd[0] == "/switch" || $cmd[0] == "/query") {
		if(trim($cmd[1]) != $channel) {
			$_SESSION['idleirc-channel'] = trim($cmd[1]);
			$logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>" . trim($cmd[1]) . " is focused, all messages will be sent to " . trim($cmd[1]) . "</td></tr>\n"; // push to client
		} else {
			$logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version</span> ~</td><td>You're already focused on $channel</td></tr>\n";
		}
	} else if ($cmd[0] == "/help" || $cmd[0] == "/?") {
		$logline .= "<tr><td class='userinfo'><span style='color:$ipcolor;'>$title $version ~</span></td>";
		$logline .= "<td>HELP: Information about $title<br />/join [channel] : Join IRC channel [channel]<br />";
        $logline .= "/archive: Archive current log file, and clear current chat history.<br />";
		$logline .= "/focus [channel|user]: Funnel messages to specific channel or user (Alias: /switch; /query)<br />";
		$logline .= "/part (channel): Part channel, part focused channel if none specified<br />";
		$logline .= "/rejoin (channel): Part, and join a channel; focused channel if none is specified<br />"; 
		$logline .= "/nick [nickname]: Change your nickname<br />";
		$logline .= "/list [channel]: List users in a channel<br />";
        $logline .= "/msg [channel|user] [msg]: Message channel, or PM 'user'<br />";
		$logline .= "/usermode [flag(s): Sets MODE flag(s) to user<br />";
		$logfile .= "/mode [channel] [flag(s)]: Sets MODE flag(s) for [channel]<br />";
		$logline .= "/channel: Prints focused channel / user (Alias: /focused)</td></tr>\n";
	} else {
		// @@ This is a work in progress
		// Sends every channel message to each channel :[
		$line .= "PRIVMSG $channel :$msg\n";
		$logline .= "<tr><td class='userinfo'><b>$nick</b> to $channel:</td><td> $msg</td></tr>\n";
	}
	
	// Get original content
	$content = file_get_contents("users/$username.log");
	echo "<table>" . nl2br(stripslashes($content)) . "</table>";
	// Grab all contents, and push to socket output file.
	file_put_contents("users/$username.log", $content . $logline);
	// Grab user message and push to IRC client
	file_put_contents("users/.$username.push", $line);
	// Throw out your user message
	//echo nl2br(stripslashes($line));
	// DONE
		
} else if (isset($_GET['userlist'])) {
    // Generate userlist
    if(file_exists("users/$username.userlist")) {
        $userListContent = file_get_contents("users/$username.userlist");
        echo $userListContent;
    } else {
        echo " ";
    }
} else if (isset($_GET['get']) && isset($_GET['nick']) && $_GET['nick']!="") {
    $nick = stripslashes(htmlentities($_GET['nick'])); // Username
    // Grab IRC client output
    $content = file_get_contents("users/$nick.log");

    if($_GET['get']=="") {
        // Push content to the web frontend
    	echo "<table>" . nl2br(stripslashes($content)) . "</table>";
    	// DONE
    } else if($_GET['get']=="notificationmentionexists") {
        if(file_exists("users/.$nick.mentioned")) {
            echo "true";
        } else {
            echo "false";
        }
    } else if($_GET['get']=="notificationpmedexists") {
        if(file_exists("users/.$nick.pmed")) {
            echo "true";
        } else {
            echo "false";
        }
    } else if($_GET['get']=="notificationmention") {
        $mentionuser = file_get_contents("users/.$nick.mentioned");
        unlink("users/.$nick.mentioned");
        echo $mentionuser;
    } else if($_GET['get']=="notificationpmed") {
        $pmuser = file_get_contents("users/.$nick.pmed");
        unlink("users/.$nick.pmed");
        echo $pmuser;
    }
} else if (isset($_GET['do']) && isset($_GET['nick']) && $_GET['nick']!="") {
	$nick = stripslashes(htmlentities($_GET['nick']));
	include("users/" . $nick . ".php");
	if ($_GET['do']=="clearlog") {
		if(file_exists("users/" . $nick . ".log") && ($acctpass == $userpass)) {
			unlink("users/$nick.log");
		}

        if(file_exists("users/" . $nick . ".logcount") && ($acctpass == $userpass)) {
            $archived = file_get_contents("users/$nick.logcount");
            for($x = 1; $x <= $archived; $x++) {
                if(file_exists("users/$nick.$x.log")) {
                    unlink("users/$nick.$x.log");
                }
            }

            unlink("users/$nick.logcount");
        }
	} else if($_GET['do']=="login" && !file_exists("users/.$username.pingfile") && ($acctpass == $userpass)) { // Is user asking for login?
		// Join channel
		$isachannel = substr_count($_SESSION['idleirc-channel'],'#') > 1 ? TRUE : FALSE ;
		if(!isset($_SESSION['idleirc-channel']) || $isachannel == FALSE) {
			file_put_contents("users/.$username.push", "JOIN " . $userchannel . "\n");
		} else {
			file_put_contents("users/.$username.push", "JOIN " . $userchannel . "\n");
		}
		
		// Make sure users DB is clean, put nothing into socket read file
		if(!file_exists("users/$username.log")) {
			file_put_contents("users/$username.log", "");
			chmod("users/$username.log", 0755); // file permissions for read / write
		}

		// start pingfile - determines if webclient is active via write timestamp 
		file_put_contents("users/.$username.pingfile", "pong");
		chmod("users/.$username.pingfile", 0755); // file permissions for read / write
		
		// Execute IRC client in background
		// IRC server will die when either 1) pingfile is deleted, or
		// 2) if pingfile is older than 10 seconds of current sys time
		$realpath = realpath("./irc.php"); // get full file path
		
		// Execute IRC client
		shell_exec("/usr/bin/php $realpath $username $servaddr $servport > /dev/null 2>/dev/null &"); 
	} else if($_GET['do']=="logout" && ($acctpass == $userpass)) { // Is user asking for logout?
		// Remove ping file if user logs out. IRC server will close
		$content = file_get_contents("users/$nick.log");
		file_put_contents("users/$nick.log", $content . "<tr><td class='userinfo'><b>$usernick</b> ~ </td><td> left the server...</td></tr>\n");
		unlink("users/.$nick.pingfile");
	}
}
?>	
